<template>
  <div class="map-container" :style="{ width: mapWidth + 'px' }">
    <div id="container" class="map-container"></div>

    <!-- 自定义标记模板 (隐藏) -->
    <div class="marker-templates" style="display: none;">
      <!-- 标记点样式模板 -->
      <div class="custom-marker-template">
        <div class="marker-wrapper">
          <img :src="markerIcon" class="marker-icon" />
          <div class="marker-label"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, watch } from "vue"
import AMapLoader from "@amap/amap-jsapi-loader"
import { ElMessage } from "element-plus"
import { useLocationStore } from '@/stores/LocationStore'

let map = null
let markers = [] // 存储所有标记
const locationStore = useLocationStore()
const walkingRoute = ref(null)
const isCalculating = ref(false)
const markerIcon = new URL('@/assets/map-marker.png', import.meta.url).href
const routes = ref(new Map())
const mapWidth = ref(0)
const emit = defineEmits(['map-loaded'])

//初始化地理位置，根据用户网页使用的ip进行定位
const initGeolocation = (AMap, map) => {
  AMap.plugin('AMap.Geolocation', () => {
    const geolocation = new AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
      zoomToAccuracy: true,
    })

    map.addControl(geolocation)

    geolocation.getCurrentPosition((status, result) => {
      if (status === 'complete') {
        const position = {
          latitude: result.position.lat,
          longitude: result.position.lng
        }
        locationStore.setPosition(position)
      } else {
        console.error('定位失败：', result.message)
        ElMessage.error('定位失败')
      }
    })
  })
}

// 计算地图宽度的函数
const calculateMapWidth = () => {
  const windowWidth = window.innerWidth
  const sidebarWidth = document.querySelector('.sidebar')?.offsetWidth || 0
  mapWidth.value = windowWidth - sidebarWidth
}

// 添加标记方法，同时设置了标记点击样式与内容
const addMarker = (spot) => {
  // 创建信息窗体内容
  const infoContent = document.createElement('div')
  infoContent.className = 'info-window'
  infoContent.innerHTML = `
    <div class="info-content">
      <div class="info-header">
        <img src="${spot.image || '@/assets/map-marker.png'}" class="spot-image" />
        <h3>${spot.name}</h3>
      </div>
      <div class="info-body">
        <div class="description-wrapper" onwheel="event.stopPropagation()">
          <p class="description">${spot.description}</p>
        </div>
        <div class="info-details">
          <span class="rating">⭐ ${spot.attractionRating || '暂无评分'}</span>
          <span class="duration">⏱️ ${spot.duration || 2}小时</span>
        </div>
      </div>
    </div>
  `
  const descWrapper = infoContent.querySelector('.description-wrapper')
  descWrapper.addEventListener('wheel', (e) => {
    e.stopPropagation()
  })
  // 创建标记
  const marker = new AMap.Marker({
    position: [spot.longitude, spot.latitude],
    anchor: 'bottom-center',
    offset: new AMap.Pixel(0, -20),
    icon: new AMap.Icon({
      // 使用处理后的 URL
      image: markerIcon,
      size: new AMap.Size(40, 40),
      imageSize: new AMap.Size(40, 40)
    })
  })

  // 创建信息窗体
  const infoWindow = new AMap.InfoWindow({
    content: infoContent,
    offset: new AMap.Pixel(0, -40),
    closeWhenClickMap: true,
    autoMove: true,
    isCustom: true
  })

  // 绑定点击事件
  marker.on('click', () => {
    infoWindow.open(map, marker.getPosition())
  })

  map.add(marker)
  markers.push({ id: spot.attractionId, marker, infoWindow })

  // 平滑移动到新标记
  map.setZoomAndCenter(15, [spot.longitude, spot.latitude], false, 1000)
}


// 移除标记方法
const removeMarker = (attractionId) => {
  const index = markers.findIndex(m => m.id === attractionId)
  if (index > -1) {
    markers[index].infoWindow.close()
    map.remove(markers[index].marker)
    markers.splice(index, 1)
  }
}

// 清除所有标记
const clearMarkers = () => {
  markers.forEach(m => {
    m.infoWindow.close()
    map.remove(m.marker)
  })
  markers = []
}

// 计算步行路线,使用高德地图的步行插件，返回并保存路线信息
const calculateWalkingRoute = async (start, end) => {
  isCalculating.value = true
  try {
    const walking = new AMap.Walking({
      map: null,
      hideMarkers: true
    })

    return new Promise((resolve, reject) => {
      walking.search(
        [start.longitude, start.latitude],
        [end.longitude, end.latitude],
        (status, result) => {
          if (status === 'complete') {
            const route = result.routes[0]
            const routePolyline = new AMap.Polyline({
              path: route.steps.map(step => step.path).flat(),
              strokeColor: '#3366FF',
              strokeWeight: 6,
              strokeOpacity: 0.8,    // 添加不透明度
              isOutline: true,       // 添加描边
              outlineColor: '#FFF',  // 描边颜色
              map: null              // 初始不显示
            })

            // 存储路线信息
            const routeKey = `${start.attractionId}-${end.attractionId}-步行`
            routes.value.set(routeKey, {
              polyline: routePolyline,
              duration: Math.ceil(route.time / 60),
              distance: route.distance
            })

            resolve({
              duration: Math.ceil(route.time / 60),
              distance: route.distance,
              path: route.steps
            })
          } else {
            reject(new Error('步行路线规划失败'))
          }
        }
      )
    })
  } finally {
    isCalculating.value = false
  }
}

// 计算骑行路线
const calculateRidingRoute = async (start, end) => {
  isCalculating.value = true
  try {
    const riding = new AMap.Riding({
      map: null,
      hideMarkers: true
    })

    return new Promise((resolve, reject) => {
      riding.search(
        [start.longitude, start.latitude],
        [end.longitude, end.latitude],
        (status, result) => {
          if (status === 'complete') {
            const route = result.routes[0]
            const routePolyline = new AMap.Polyline({
              path: route.rides.map(ride => ride.path).flat(),
              strokeColor: '#00CC66',
              strokeWeight: 6,
              strokeOpacity: 0.8,
              isOutline: true,
              outlineColor: '#FFF',
              map: null
            })

            const routeKey = `${start.attractionId}-${end.attractionId}-骑行`
            routes.value.set(routeKey, {
              polyline: routePolyline,
              duration: Math.ceil(route.time / 60),
              distance: route.distance
            })

            resolve({
              duration: Math.ceil(route.time / 60),
              distance: route.distance,
              path: route.rides
            })
          } else {
            reject(new Error('骑行路线规划失败'))
          }
        }
      )
    })
  } finally {
    isCalculating.value = false
  }
}

// 计算驾车路线
const calculateDrivingRoute = async (start, end) => {
  isCalculating.value = true
  try {
    const driving = new AMap.Driving({
      map: null,
      hideMarkers: true
    })

    return new Promise((resolve, reject) => {
      driving.search(
        [start.longitude, start.latitude],
        [end.longitude, end.latitude],
        (status, result) => {
          if (status === 'complete') {
            const route = result.routes[0]
            const routePolyline = new AMap.Polyline({
              path: route.steps.map(step => step.path).flat(),
              strokeColor: '#FF3366',
              strokeWeight: 6,
              strokeOpacity: 0.8,
              isOutline: true,
              outlineColor: '#FFF',
              map: null
            })

            const routeKey = `${start.attractionId}-${end.attractionId}-驾车`
            routes.value.set(routeKey, {
              polyline: routePolyline,
              duration: Math.ceil(route.time / 60),
              distance: route.distance
            })

            resolve({
              duration: Math.ceil(route.time / 60),
              distance: route.distance,
              path: route.steps
            })
          } else {
            reject(new Error('驾车路线规划失败'))
          }
        }
      )
    })
  } finally {
    isCalculating.value = false
  }
}

// 切换路线显示状态，可以用于显示、隐藏或删除路线
const toggleRoute = (startId, endId, type, remove = false, visible) => {
  console.log('路线控制:', {
    startId,
    endId,
    type,
    remove,
    visible,
    operation: remove ? '删除' : (visible === undefined ? '切换' : (visible ? '显示' : '隐藏'))
  })

  if (!startId || !endId || !type) {
    console.error('参数无效:', { startId, endId, type })
    return
  }

  const routeKey = `${startId}-${endId}-${type}`
  const route = routes.value.get(routeKey)

  if (!route) {
    console.warn('未找到路线:', routeKey)
    console.log('当前路线集合:', Array.from(routes.value.keys()))
    return
  }

  if (remove) {
    route.polyline.setMap(null)
    routes.value.delete(routeKey)
    console.log('路线已删除:', routeKey)
    return
  }

  // 如果提供了 visible 参数，直接设置显示状态
  // 否则切换当前状态
  const currentMap = route.polyline.getMap()
  const newVisible = visible !== undefined ? visible : !currentMap
  route.polyline.setMap(newVisible ? map : null)

  console.log('路线状态更新:', {
    routeKey,
    原状态: !!currentMap,
    新状态: newVisible
  })
}

// 清除指定路线
const clearRoute = (startId, endId, type) => {
  const routeKey = `${startId}-${endId}-${type}`
  const route = routes.value.get(routeKey)
  if (route) {
    route.polyline.setMap(null)
    routes.value.delete(routeKey)
  }
}

// 清除所有路线
const clearAllRoutes = () => {
  routes.value.forEach(route => {
    route.polyline.setMap(null)
  })
  routes.value.clear()
}

// 监听窗口大小变化
const handleResize = () => {
  calculateMapWidth()
  // 如果地图实例存在，触发重新绘制
  if (map) {
    map.resize()
  }
}
onMounted(() => {
  // 初始计算宽度
  calculateMapWidth()

  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)

  window._AMapSecurityConfig = {
    securityJsCode: "60e37c35a3c82bdf46e766cdae8c40f9",  // 安全密钥
  }

  AMapLoader.load({
    key: "66d50e7c4e1242e421eee929edf5d145", // Web端开发者Key
    version: "2.0",
    plugins: [
      "AMap.Scale",
      "AMap.Geolocation",
      "AMap.MarkerClusterer",
      "AMap.Walking",     // 步行插件
      "AMap.Riding",      // 骑行插件
      "AMap.Driving"      // 驾车插件
    ], // 添加聚合插件
  })
    .then((AMap) => {
      map = new AMap.Map("container", {
        viewMode: "3D",
        zoom: 11,
        center: [121.553958, 29.869472]
      })

      initGeolocation(AMap, map)
      console.log('地图加载完成')
      emit('map-loaded')
    })
    .catch((e) => {
      console.error('地图加载失败:', e)
      ElMessage.error('地图加载失败')
    })
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  markers.forEach(m => m.infoWindow.close())
  map?.destroy()
})

defineExpose({
  recalculateWidth: calculateMapWidth,
  addMarker,
  removeMarker,
  clearMarkers,
  calculateWalkingRoute,
  calculateRidingRoute,
  calculateDrivingRoute,
  toggleRoute,
  clearRoute,
  clearAllRoutes
})
</script>

<style scoped>
.map-container {
  transition: width 0.3s ease;
  height: 100vh;
  will-change: width;
}

.map-content {
  width: 100%;
  height: 100%;
}

/* 信息窗体样式 */
:deep(.info-window) {
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  max-width: 300px;
}

:deep(.info-header) {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
}

:deep(.description-wrapper) {
  max-height: 100px;
  /* 设置描述文本最大高度 */
  overflow-y: auto;
  /* 只启用垂直滚动 */
  margin-bottom: 10px;
  /* 与下方详情保持间距 */
  /* 添加平滑滚动效果 */
  scroll-behavior: smooth;
  /* 确保内容可以滚动 */
  -webkit-overflow-scrolling: touch;
}

/* 描述文本滚动条样式 */
:deep(.description-wrapper::-webkit-scrollbar) {
  width: 4px;
}

:deep(.description-wrapper::-webkit-scrollbar-thumb) {
  background-color: #dcdfe6;
  border-radius: 2px;
}

:deep(.description-wrapper::-webkit-scrollbar-track) {
  background-color: #f5f7fa;
  border-radius: 2px;
}

:deep(.spot-image) {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
  margin-right: 12px;
}

:deep(.info-header h3) {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

:deep(.info-body) {
  color: #666;
}

:deep(.description) {
  margin: 8px 0;
  line-height: 1.5;
  font-size: 14px;
}

:deep(.info-details) {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  color: #888;
  font-size: 13px;
}

:deep(.rating) {
  color: #ff9900;
}

:deep(.duration) {
  color: #409EFF;
}

/* 自定义标记样式 */
.marker-wrapper {
  position: relative;
  width: 40px;
  height: 40px;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.marker-wrapper:hover {
  transform: scale(1.1);
}

.marker-icon {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
</style>